{% extends "../base.html" %}

{% block body %}
  <div style="text-align: center">
    <h3>{{ entry['title'] }}</br></br>
      <small>{{ author['name'] }}&nbsp;</small>
      <small>
        {% if entry.get('updated', None) %}
          最后一次修改于 {{ datetime.datetime.fromtimestamp(entry['updated']).strftime('%Y-%m-%d %H:%M:%S') }}
        {% else %}
          创建于 {{ datetime.datetime.fromtimestamp(entry['created']).strftime('%Y-%m-%d %H:%M:%S') }}
        {% end %}
      </small>
    </h3>
  </div>

  <br/><br/>

  {% for p in entry['text'].splitlines() %}
    <p class="paragraph">{{ p }}</p>
  {% end %}

  {% if current_user and current_user['_id'] == entry['author'] %}
    <a class="btn btn-sm btn-info" href={{ '/entry/edit?_id=%s' % entry['_id'] }}>编辑</a>
    <a class="btn btn-sm btn-danger" data-toggle="modal" data-target="#alertModal">删除</a>
    {% module Modal('删除', '/entry/delete/%s' % entry['_id']) %}
  {% end %}

  <br/><hr/>

  <textarea id="text" name="text" class="form-control"></textarea>
  <p></p>
  <button id="btn-submit" class="btn btn-primary">提交评论</button>
  <p></p>
  <span id="notify"></span>
  {% module xsrf_form_html() %}

  <hr/>

  <div>
    <ul id="comments">
      {% if comments %}
        {% for cmt in comments %}
          <li>
            {% module Comment(cmt) %}
          </li>
        {% end %}
      {% end %}
    </ul>
  </div>
{% end %}

{% block bottom%}
  <script type="text/javascript">
    $("#btn-submit").click(function () {
      if (!getCookie('user_id')) {
        alert("请先登录！");
        window.location.replace('/auth/login');
        return null;
      }
      var text = $("#text").val();
      if (!text) {
        $("#notify").html('<div class="alert alert-danger">'
                          + '<button class="close" data-dismiss="alert">&times;</button>'
                          + '评论内容不能为空！'
                          + '</div>');
        return null;
      }
      $.ajax({
        url: "/entry/comment",
        type: "POST",
        data: {
          "text": text,
          "author": "{{ current_user['_id'] if current_user else '' }}",
          "entry": "{{ entry['_id'] }}"
        },
        success: function (comment) {
          $("#comments").append("<li>" + comment + "</li>");
          $("#text").val("");
          $("#notify").html("");
        }
      });
    });
  </script>
{% end %}
